package com.luqili.utils.pub.network;

import com.luqili.utils.pub.link.Pair;
import org.apache.commons.codec.binary.Hex;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 网络工具
 *
 * @author luqili
 */
public class NetWorkUtils {

    /**
     * 获得当前正在使用的Mac地址及IP4地址
     *
     * @return
     */
    public static Pair<String, String> getUseMacIp4Address() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                if (ni.isUp() && ni.getHardwareAddress() != null) {
                    String macAddress = Hex.encodeHexString(ni.getHardwareAddress());
                    for (InterfaceAddress ipadd : ni.getInterfaceAddresses()) {
                        InetAddress ia = ipadd.getAddress();
                        if (ia.getAddress().length == 4) {
                            String ipAddress = ia.getHostAddress();
                            return new Pair<String, String>(macAddress, ipAddress);
                        }

                    }
                }
            }
        } catch (Exception e) {
        }
        return null;
    }

}
